import React, { useState, useCallback, useEffect } from 'react';
import { Common } from 'UtilsCommon';
import Base from './base';

const valueChange = (property, view, checked) => {
    const value = checked ? 1 : 0;
    if (property.valueChange) property.valueChange(value);

    if (property.valueVisibleProperties) Base.setValueVisibleProperties(property, view, value);
};

const getValue = (property, checked) => {
    if (property.checkValue) {
        return checked ? property.checkValue : property.unCheckValue;
    }
    return checked ? 1 : 0;
};

const getChecked = (property, value) => {
    return Common.isNullOrEmpty(value) ? false : property.checkValue ? Common.isEquals(value, property.checkValue) : parseInt(value, 10) === 1;
};

export default React.memo((props) => {
    const { property, view } = Base.getProps(props);

    const [checked, setChecked] = useState(property, getChecked(Base.getInitValue(property)));
    const [isVisible, setIsVisible] = useState(property.isVisible !== false);

    const onChange = useCallback(() => {
        setChecked(!checked);
    }, [property, checked, setChecked]);

    useEffect(() => {
        valueChange(property, view, checked);
    }, [property, view, checked]);

    property.setIsVisible = (v) => { property.isVisible = v; setIsVisible(v); };
    property.setValue = (v) => setChecked(getChecked(property, v));
    property.getValue = () => getValue(property, checked);

    if (!isVisible) return null;

    const { style, labelStyle, label, text, isAddColon, onImgUrl, offImgUrl, itemStyle, textStyle } = property;

    const checkStyle = property.checkStyle;
    checkStyle.backgroundImage = checked ? onImgUrl : offImgUrl;

    return <div style={Base.setStyle(style)}>
        {label && <div style={Base.setStyle(labelStyle)}>{label}{isAddColon ? '：' : ''}</div>}
        <div style={Base.setStyle(itemStyle)} className='buttonActive' onClick={onChange}>
            <div style={Base.setStyle(checkStyle)}></div>
            <div style={Base.setStyle(textStyle)}>{text}</div>
        </div>
    </div>;
});
